<?php
/**
 * Created by Boume.
 * Date: 4/29 0029
 * Time: 23:19
 */
namespace app\admin\controller;

use app\admin\model\Admin;
use app\admin\model\Auth;
use app\admin\model\Node;
use think\facade\Validate;
use tool\Crypt;
use tool\Tree;

class Index extends Base
{
    public function index()
    {
        //获取节点列表
        $lists = Node::where('show', '1')->order('sort asc')->column('*', 'id');
        if (session('U.role_id') > 1) {
            $nids = Auth::where('rid', session('U.role_id'))->column('nid');
            foreach ($lists as $k => $v) {
                if (!in_array($k, $nids)) unset($lists[$k]);
            }
        }
        $Tree = new Tree();
        $menu = $Tree->getTree9($lists);
        $this->assign('menu', $menu);
        return $this->fetch();
    }

    public function console()
    {
        $edit_password_time = ceil((time() - session('U.edit_password_time')) / (60 * 60 * 24));
        $this->assign('edit_password_time', $edit_password_time);
        return $this->fetch();
    }

    public function modify_pwd()
    {
        if ($this->request->isPost()) {
            $rule = [
                'password' => 'require|alphaDash|confirm',
            ];
            $msg = [
                'password.require' => '密码必填',
                'password.alphaDash' => '密码只能是字母、数字、“_”、“-”',
                'password.confirm' => '两次密码不一致',
            ];
            $validate = Validate::make($rule, $msg);
            $post = input('post.');
            $result = $validate->check($post);
            if (!$result) $this->error($validate->getError());
            $Crypt = new Crypt();
            $password = $Crypt->encrypt($post['password']);
            $Admin = new Admin();
            $Admin->save([
                'password' => $password,
                'edit_password_time' => time(),
            ],[
                'id' => session('U.id')
            ]);
            return json([
                'code' => 1,
                'msg' => '密码修改成功',
                'url' => url('passport/logout')
            ]);
        } else {
            return $this->fetch();
        }
    }

    public function modify_my()
    {
        $Admin = new Admin();
        $id = session('U.id');
        if ($this->request->isPost()) {
            $Admin->save([
                'name' => input('param.name'),
                'mobile' => input('param.mobile'),
            ], [
                'id' => $id
            ]);
            return json([
                'code' => 1,
                'msg' => '个人资料修改成功'
            ]);
        } else {
            $data = $Admin->get($id);
            $this->assign('data', $data->getData());
            return $this->fetch();
        }
    }
}